//
//  GCDTcpSocketManager.m
//  fireplace
//
//  Created by XiangDongMBP on 2017/3/17.
//  Copyright © 2017年 East. All rights reserved.
//

#import "GCDTcpSocketManager.h"
#import <GCDAsyncSocket.h>

NSNotificationName const FIPGCDSocketStatusChanged = @"FIPGCDSocketStatusChanged";
NSNotificationName const FIPGCDSyncHotStatus = @"FIPGCDSyncHotStatus";
NSNotificationName const FIPGCDSyncRGBStatus = @"FIPGCDSyncRGBStatus";
NSNotificationName const FIPGCDSyncRGBMode = @"FIPGCDSyncRGBMode";

@interface GCDTcpSocketManager ()<GCDAsyncSocketDelegate>

@property (nonatomic, assign) GCDSocketConnectStatus connectStatus;
@property (nonatomic, assign) NSInteger hot;
@property (nonatomic, assign) BOOL ledOn;
@property (nonatomic, assign) NSInteger brightness;
@property (nonatomic, assign) NSInteger speed;
@property (nonatomic, assign) NSInteger rgbModel;
@property (nonatomic, assign) NSInteger rgbColor;

@property (nonatomic, strong) GCDAsyncSocket *socket;
@property (nonatomic, strong) NSTimer *beatTimer;       //!< 心跳定时器(每隔5s发送一个连接请求)
@property (nonatomic, strong) NSTimer *reconnectTimer;  //!< 重连定时器()

@end

static NSString *const kServerHost = @"10.10.100.250";  //!< 服务器IP
static uint16_t  const kServerPort = 8899;              //!< 端口
static NSInteger const kConnectTimeout = 30;            //!< 连接超时30s

@implementation GCDTcpSocketManager

#pragma mark - API
+ (instancetype)sharedInstance {
    static GCDTcpSocketManager *manager;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        manager = [[GCDTcpSocketManager alloc] init];
    });
    
    return manager;
}
- (void)connetToHost {
    if (self.connectStatus != -1) {
        NSLog(@"Socket Connect: YES");
        return;
    }
    
    self.connectStatus = 0;
    
    NSError *error;
    BOOL result;
    result = [self.socket connectToHost:kServerHost onPort:kServerPort withTimeout:kConnectTimeout error:&error];
    if (!result) {
        self.connectStatus = -1;
        NSLog(@"connectToHost error:%@", error);
    }
}
- (void)disconnet {
    
}
- (void)startBeat {
    ;
}
- (void)endBeat {
    ;
}
- (void)configHot:(NSInteger)hot {
    ;
}
- (void)configBrightness:(NSInteger)brightness {
    ;
}
- (void)configSpeed:(NSInteger)speed {
    ;
}
- (void)configRgbMode:(NSInteger)mode rgbColor:(NSInteger)rgbColor {
    ;
}

#pragma mark - GCDAsyncSocketDelegate
- (void)socket:(GCDAsyncSocket *)sock didConnectToHost:(NSString *)host port:(uint16_t)port {
    NSLog(@"连接到主机:%@ %zd", host, port);
    self.connectStatus = 1;
    // 发送通知，表明socket状态发生变化
}
- (void)socketDidDisconnect:(GCDAsyncSocket *)sock withError:(NSError *)err {
    NSLog(@"断开连接:%@", err);
    self.connectStatus = -1;
    // 发送通知，表明socket状态发生变化
}

#pragma mark - Socket操作
//- (void)write

#pragma mark - gettes and setters
- (GCDAsyncSocket *)socket {
    if (!_socket) {
        _socket = [[GCDAsyncSocket alloc] initWithDelegate:self delegateQueue:dispatch_get_main_queue()];
    }
    return _socket;
}

@end
